package com.wyj.longrangeclient.Service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.wyj.longrangeclient.MainActivity;
import com.wyj.longrangeclient.R;
import com.wyj.longrangeclient.Util.RxBus;

import java.nio.ByteBuffer;
import java.util.Objects;

import rx.Observer;

/**
 * author : 泥菩萨
 * time   : 2023/04/14
 */
public class ScreenRecorder extends Service {

   private VirtualDisplay mVirtualDisplay;

   private WindowManager mWindowManager;
   private int mWindowWidth,mWindowHeight;

   private ImageReader mImageReader;

   private int mScreenDensity;


   @Nullable
   @Override
   public IBinder onBind(Intent intent) {
      return null;
   }

   @Override
   public void onCreate() {
      super.onCreate();

      //用来让service不进入闲置 避免被回收
      RxBus.getInstance().Register("ScreenRecorder", new Observer<Object>() {

         @Override
         public void onCompleted() {

         }

         @Override
         public void onError(Throwable e) {

         }

         @Override
         public void onNext(Object o) {

            RxBus.getInstance().post("ServiceMsg","录屏服务:正在运行");
         }
      });
   }

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {

      createNotificationChannel();

      int mResultCode = intent.getIntExtra("code", -1);
      Intent mResultData = intent.getParcelableExtra("data");

      MediaProjectionManager mMediaProjectionManager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE);

      try {

         mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
         mWindowWidth = mWindowManager.getDefaultDisplay().getWidth();
         mWindowHeight = mWindowManager.getDefaultDisplay().getHeight();
         mImageReader = ImageReader.newInstance(mWindowWidth, mWindowHeight, PixelFormat.RGBA_8888, 2);
         DisplayMetrics displayMetrics = new DisplayMetrics();
         mWindowManager.getDefaultDisplay().getMetrics(displayMetrics);
         mScreenDensity = displayMetrics.densityDpi;

         MediaProjection mMediaProjection = mMediaProjectionManager.getMediaProjection(mResultCode, Objects.requireNonNull(mResultData));

         mVirtualDisplay = mMediaProjection.createVirtualDisplay("ScreenCapture", mWindowWidth, mWindowHeight, mScreenDensity,
                 DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), null, null);

         mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader imageReader) {

               Image image = mImageReader.acquireLatestImage();
               if (image==null)return;
               int width = image.getWidth();
               int height = image.getHeight();
               final Image.Plane[] planes = image.getPlanes();
               final ByteBuffer buffer = planes[0].getBuffer();
               int pixelStride = planes[0].getPixelStride();
               int rowStride = planes[0].getRowStride();
               int rowPadding = rowStride - pixelStride * width;
               Bitmap mBitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888);
               mBitmap.copyPixelsFromBuffer(buffer);
               mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, width, height);

               mBitmap = Bitmap.createScaledBitmap(mBitmap,width/4,height/4,false);

               RxBus.getInstance().post("bitmap",mBitmap);
               image.close();

            }
         },null);

      }catch (Exception e){

         String msg = e.getMessage();
      }

      return super.onStartCommand(intent, flags, startId);
   }

   private void createNotificationChannel() {

      Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
      Intent nfIntent = new Intent(this, MainActivity.class); //点击后跳转的界面，可以设置跳转数据

      builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
              .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.ic_launcher)) // 设置下拉列表中的图标(大图标)
              .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
              .setContentText("is running......") // 设置上下文内容
              .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

      /*以下是对Android 8.0的适配*/
      //普通notification适配
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         builder.setChannelId("notification_id");
      }
      //前台服务notification适配
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
         NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
         NotificationChannel channel = new NotificationChannel("notification_id", "notification_name", NotificationManager.IMPORTANCE_LOW);
         notificationManager.createNotificationChannel(channel);
      }

      Notification notification = builder.build(); // 获取构建好的Notification
      notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
      startForeground(110, notification);
   }

   @Override
   public void onDestroy() {
      super.onDestroy();

      if (mVirtualDisplay != null) {
         mVirtualDisplay.release();
         mVirtualDisplay = null;
      }

      RxBus.getInstance().Cancellation("ScreenRecorder");
      RxBus.getInstance().post("ServiceMsg","录屏服务:关闭");
   }
}
